package com.young.app.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import com.sun.javafx.binding.StringFormatter;
import com.young.app.model.User;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.ArrayList;
import java.util.List;

/**
 * TODO
 *
 * @author ：young
 * @date ：Created in 2020/3/10
 */
public class SimpleExcelListener extends AnalysisEventListener<User> {
    private static Logger logger = LogManager.getLogger(SimpleExcelListener.class);

    private void saveData() {
        logger.info(StringFormatter.format("{%d}条数据，开始存储数据库！\n", list.size()).getValueSafe());
        logger.info("存储数据库成功！");
    }

    /**
     * 阈值 一次读取行数
     */
    private static final int BATCH_COUNT = 10;
    List<User> list = new ArrayList<User>(BATCH_COUNT);

    @Override
    public void invoke(User user, AnalysisContext analysisContext) {
        logger.info(StringFormatter.format("解析到一条数据:{%s}\n", JSON.toJSONString(user)).getValueSafe());
        list.add(user);
        if (list.size() >= BATCH_COUNT) {
            saveData();
            list.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        /**
         * EXCEL_DATA_TOTAL % {@value BATCH_COUNT} >0
         */
        saveData();
        logger.info("所有数据解析完成！");
    }
}
